import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Layout from '../layout/index.vue'
import Dashboard from '../views/Dashboard.vue'
import UserList from '../views/user/UserList.vue'
import DocumentList from '../views/document/DocumentList.vue'
import CategoryList from '../views/document/CategoryList.vue'
import TagList from '../views/tag/TagList.vue'
import CaseList from '../views/case/CaseList.vue'
import LawList from '../views/law/LawList.vue'
import CommentList from '../views/comment/CommentList.vue'

const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresGuest: true } // 已登录用户不能访问登录页
  },
  {
    path: '/',
    component: Layout,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { requiresAuth: true }
      },
      {
        path: 'user/list',
        name: 'UserList',
        component: UserList,
        meta: { requiresAuth: true }
      },
      {
        path: 'document/list',
        name: 'DocumentList',
        component: DocumentList,
        meta: { requiresAuth: true }
      },
      {
        path: 'document/category',
        name: 'CategoryList',
        component: CategoryList,
        meta: { requiresAuth: true }
      },
          {
            path: 'tag/list',
            name: 'TagList',
            component: TagList,
            meta: { requiresAuth: true }
          },
          {
            path: 'case/list',
            name: 'CaseList',
            component: CaseList,
            meta: { requiresAuth: true }
          },
          {
            path: 'law/list',
            name: 'LawList',
            component: LawList,
            meta: { requiresAuth: true }
          },
          {
            path: 'comment/list',
            name: 'CommentList',
            component: CommentList,
            meta: { requiresAuth: true }
          }
      // 后续其他页面路由都放在这里
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果目标路由需要登录且用户未登录
  if (to.meta.requiresAuth && !token) {
    next('/login')
    return
  }
  
  // 如果目标路由是给未登录用户的（如登录页）且用户已登录
  if (to.meta.requiresGuest && token) {
    next('/dashboard')
    return
  }
  
  next()
})

export default router
